package com.liang;

/**
 * 模拟CAS算法
 *
 * @author: Liangxp
 * @date: 2019/7/30 20:48
 */
public class TestCompareAndSwap3 {
    public static void main(String[] args) {
        CompareAndSwap compareAndSwap = new CompareAndSwap();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int expectedValue = compareAndSwap.get();
                    boolean b = compareAndSwap.compareAndSet(expectedValue, (int)(Math.random() * 101));
                    System.out.println(b);
                }
            }).start();
        }
    }
}

class CompareAndSwap {
    private int value;

    // 获取内存值
    public synchronized int get() {
        return this.value;
    }

    /**
     * 比较
     * @param expectedValue 预估值
     * @param newValue 更新值
     * @return
     */
    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = this.value;
        if (expectedValue == oldValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    /**
     * 设置
     * @param expectedValue
     * @param newValue
     * @return
     */
    public synchronized boolean compareAndSet(int expectedValue, int newValue) {
        return expectedValue == compareAndSwap(expectedValue, newValue);
    }
}
